<template>
  <a-spin :spinning="formState.uploadImgLoading">
    <page-layout class="add-project-box">
      <a-row :gutter="[10, 10]">
        <!-- 顶部区域 -->
<!--        <a-col :span="24">-->
<!--          <a-card>-->
<!--            <div class="box-ver-hor-between">-->
<!--              <div class="primary-color">新增项目</div>-->
<!--              <div>-->
<!--                <a-button type="primary"  @click="save">-->
<!--                  保存-->
<!--                </a-button>-->
<!--              </div>-->
<!--            </div>-->
<!--          </a-card>-->
<!--        </a-col>-->

        <a-col :span="24">
          <a-form ref="formRef" :model="formState.data" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-card title="基础信息">
              <a-row>
                <a-col :span="8">
                  <a-form-item label="项目名称"
                               name="projectName"
                               :rules="[
                                 {required: true, message: '请输入项目名称', trigger: 'blur'}
                               ]"
                  >
                    <a-input v-model:value="formState.data.projectName" placeholder="请输入"/>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="合作学校" name="schName">
                    <a-input class="pointer-input"
                             v-model:value="formState.data.schName"
                             readonly
                             placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('schName')">选择</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="主办方联系人" name="contactsName">
                    <a-input class="pointer-input"
                             v-model:value="formState.data.contactsName"
                             readonly
                             placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('responsiblePerson')">选择</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="负责人" name="responsiblePerson">
                    <a-input v-model:value="formState.data.responsiblePerson" readonly placeholder="请选择">
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('contactsName')">选择</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="进度" name="speedProgress">
                    <a-select v-model:value="formState.data.speedProgress" placeholder="请选择">
                      <a-select-option v-for="item in dictLists.data[dictEnum.FOLLOW_PROGRESS]"
                                       :key="item.id"
                                       :value="item.value">{{item.label}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="项目地址" name="projectAddress">
                    <a-input v-model:value="formState.data.projectAddress" placeholder="请输入" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="预计规模" name="estimatedScale">
                    <a-input v-model:value="formState.data.estimatedScale"
                             suffix="元"
                             placeholder="请输入"
                             :rules="[
                               {
                                pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]{1,2}?$)/,
                                message: '请输入正确的金额且金额小数点后保留两位',
                                trigger: 'blur'
                               }
                             ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="备注" :label-col="{ span: 3 }" name="projectDesc">
                    <a-textarea v-model:value="formState.data.projectDesc" placeholder="请输入" :rows="textareaRows"/>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row v-for="(item, _index) in formState.data.projectCharge" :key="_index">
                <a-col :span="8">
                  <a-form-item label="参与方">
                    <a-input v-model:value="item.schoolName"
                             readonly
                             class="pointer-input"
                             placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('schName', _index)">选择</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="参与方联系人">
                    <a-input v-model:value="item.chargeName"
                             readonly
                             class="pointer-input"
                             placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('responsiblePerson', _index)">选择</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-button class="ml-20" @click="addParticipants" v-if="_index <= 0">添加</a-button>
                <a-button class="ml-20" type="danger" v-if="_index >= 1" @click="deleteParticipants(_index)">删除</a-button>
              </a-row>
            </a-card>
            <a-card title="附件信息">
              <a-form-item label="附件" :label-col="{ span: 3 }" :wrapper-col="{ span: 6 }">
                <a-upload
                  name="file"
                  :multiple="true"
                  action=""
                  :headers="headers"
                  :before-upload="beforeUpload"
                  :showUploadList="false"
                >
                  <a-button>
                    <upload-outlined></upload-outlined>
                    上传文件
                  </a-button>
                </a-upload>
                <template v-if="formState.data.files.length > 0">
                  <p v-for="(item, i) in formState.data.files" :key="item.fileId" class="mt-10">
                    {{ item.name }}
                    <DeleteOutlined class="ml-10 cursor-pointer" @click.prevent.stop="() => handleDelUpload(i)"/>
                  </p>
                </template>
              </a-form-item>
            </a-card>
          </a-form>
        </a-col>
      </a-row>
    </page-layout>
    <BasicTableModal v-model:visible="modalConfig.visible"
                     v-if="modalConfig.visible"
                     :columns="modalConfig.columns"
                     :fetchAjax="modalConfig.api"
                     :searchParams="modalConfig.searchParams"
                     @selectUniversity="value => selectItem(value, modalConfig.type, modalConfig.currentIndex)"
    />
    <footer-button :buttons="formState.buttons" />
  </a-spin>
</template>

<script setup>
import {reactive, ref, onMounted, onActivated} from 'vue'
import { upload } from '@/api/module/oss'
import BasicTableModal from '@/component/basic-table-modal'
import { page as schoolPage } from '@/api/module/school'
import { page as userPage } from '@/api/module/user'
import { page as contactPage } from '@/api/module/contact-manage'
import { save as projectSave, update, selectById } from '@/api/module/project'
import dictEnum from '@/const/dict'
import { getDictByCodesReturnObj } from '@/tools/get-dict'
import {message} from "ant-design-vue";
import {useRouter, useRoute} from "vue-router";

const textareaRows = 3
const labelCol = { span: 9 }

const formState = reactive({
  uploadImgLoading: false,
  buttons: [
    {
      name: 'save',
      event: () => save(),
      type: "primary",
      code: ''
    },
    {
      name: 'reset',
      event: () => resetForm(),
      code: ''
    }
  ],
  data: {
    projectName: '',
    schName: '',
    schId: '',
    contactsId: '',
    contactsName: '',
    responsiblePerson: '',
    responsiblePersonId: '',
    speedProgress: null,
    projectAddress: '',
    estimatedScale: '',
    projectDesc: '',
    projectCharge: [],
    files: [],
  }
});
const router = useRouter()
const route = useRoute()
const formRef = ref(null)
let dictLists = reactive({
  data: {}
})
const modalConfig = reactive({
  api: schoolPage,
  type: '',
  visible: false,
  columns: [],
  currentIndex: undefined,
  searchParams: {
    name: '1'
  },
  schoolColumns: [
    { dataIndex: "schoolCnName", key: "schoolCnName", title: "学校中文名" },
    { dataIndex: "schoolEnName", key: "schoolEnName", title: "学校英文名", },
    {
      dataIndex: "schFollowUpProgress",
      key: "schFollowUpProgress",
      title: "跟进进度",
      cellRender: (record, data) => {
        if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
          const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(v => v.value == data)
          return item ? item.label : ''
        }
        return ''
      }
    },
  ],
  userColumns: [
    { dataIndex: "nickname", key: "nickname", title: "用户名称" },
    { dataIndex: "deptName", key: "deptName", title: "所属部门" },
    { dataIndex: "postName", key: "postName", title: "职位" },
  ],
  contactColumns: [
    { dataIndex: "contactsName", key: "contactsName", title: "联系人姓名" },
    { dataIndex: "contactsPosition", key: "contactsPosition", title: "职位" },
    { dataIndex: "contactsDepartment", key: "contactsDepartment", title: "所属部门" },
  ]
})

const openDialog = (type, _index) => {
  modalConfig.currentIndex = _index
  modalConfig.visible = true
  modalConfig.type = type
  modalConfig.api = type === 'schName' ? schoolPage : type === 'contactsName' ? userPage : contactPage
  modalConfig.columns =
    type === 'schName' ? modalConfig.schoolColumns : type === 'contactsName' ? modalConfig.userColumns : modalConfig.contactColumns
}

const handleDelUpload = index => {
  formState.data.files = formState.data.files.filter((v, i) => i !== index)
}

const save = () => {
  formRef.value.validate().then(() => {
    formState.uploadImgLoading = true
    if (route.query.id) {
      editItem(formState.data)
    } else {
      saveItem(formState.data)
    }
  })
}

const editItem = (data) => {
  update(data).then(res => {
    if (res.code === 200) {
      message.success(res.message)
      router.push('/university/project-manage-list')
    }
    if (res.code === 500) return message.error(res.msg || '编辑失败，服务器错误')
    formState.uploadImgLoading = false
  }).catch(() => formState.uploadImgLoading = false)
}

const saveItem = (data) => {
  projectSave(data).then(res => {
    formState.uploadImgLoading = false
    if (res.code === 200) {
      message.success(res.message)
      router.push('/university/project-manage-list')
    }
    if (res.code === 500) return message.error(res.msg || '新增失败，服务器错误')
  }).catch(() => formState.uploadImgLoading = false)
}

const resetForm = () => {
  formRef.value.resetFields()
}

const openModal = (type) => {
  formState.data[type] = true
}

const selectItem = (value, type, index) => {
  if (index || index === 0) {
    if (type === 'schName') {
      formState.data.projectCharge[index].schoolId = value.id
      formState.data.projectCharge[index].schoolName = value.schoolCnName
    } else {
      formState.data.projectCharge[index].chargeId = value.id
      formState.data.projectCharge[index].chargeName = value.nickname
    }
  } else {
    if (type === 'schName') {
      formState.data.schId = value.id
      formState.data.schName = value.schoolCnName
    } else if (type === 'contactsName') {
      formState.data.contactsId = value.id
      formState.data.contactsName = value.nickname
    } else {
      formState.data.responsiblePerson = value.contactsName
      formState.data.responsiblePersonId = value.id
    }
  }
}

const addParticipants = () => {
  formState.data.projectCharge.push({
    chargeId: '',
    chargeName: '',
    schoolId: '',
    schoolName: ''
  })
}

const deleteParticipants = (index) => {
  formState.data.projectCharge = formState.data.projectCharge.filter((v, i) => i !== index)
}

const beforeUpload = file => {
  if (!formState.uploadImgLoading) {
    formState.uploadImgLoading = true
    const Files = new FormData()
    Files.append('file', file)
    upload(Files).then(res => {
      if (res.code === 500) {
        message.error({ content: res.msg })
      } else {
        const { path: url, id: fileId, remark, name } = res.data
        const obj = {
          businessType: 'pro',
          fileId,
          url,
          remark,
          type: 2,
          name
        }
        formState.data.files.push(obj)
      }
      formState.uploadImgLoading = false
    }).catch(() => formState.uploadImgLoading = false)
  }
  return false
};

const getDictList = async () => {
  dictLists.data = await getDictByCodesReturnObj([
    dictEnum.FOLLOW_PROGRESS,
  ])
}

onActivated(() => {
  formRef.value.resetFields()
  console.log(route.query.id, 'route.query.id')
  if (route.query.id) {
    selectById({
      id: route.query.id
    }).then(res => {
      if (res.code === 500) return message.error(res.msg || '服务器错误')
      if (res.code === 200) {
        formState.data = {
          ...formState.data,
          ...res.data
        }
        if (!res.data.projectCharge || res.data.projectCharge.length <= 0) {
          formState.data.projectCharge = [
            {
              chargeId: '',
              chargeName: '',
              schoolId: '',
              schoolName: ''
            }
          ]
        }
      }
    })
  }
  addParticipants()
  getDictList()
})

</script>

<style lang="less" scoped>
.add-project-box {
  .pointer-input {
    /deep/.ant-input {
      cursor: pointer;
    }
  }
}
</style>
